import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import Shopfoot from '../index/Shopfoot'
import '../../assets/animate.min.scss'
import './mall.scss'
import './shopcar.scss'

import lbicon2 from './images/lbicon2.png'
import lbicon from './images/lbicon.png'
export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
     height:0,
	   carlist:[],
     carindex:[],
     total:0,
     isdel:0,
     malltype:'',
     appmark:CommonJs.getmark()
    }
  }
  config = {
    navigationBarTitleText: '加载中'
  }

  open(url,type){
    this.$preload({
      type:type
    })
    CommonJs.open(url);
  }


  componentWillMount () {
    this.getscreeninfo();
    // this.getcar();
    if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
    	var malltype=this.$router.preload.malltype
    	if(malltype){
	    	this.setState({
	        malltype:malltype
	      })
	    }
      this.getcar(malltype);
    } 
  }


  componentDidMount () { }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  getscreeninfo(){
	var _this=this;
	Taro.getSystemInfo({
	  success:function(res){
		var windowHeight = res.windowHeight;
		_this.setState({
		  height:windowHeight
		})
	  }
	})
  }

  getcar(malltype){
    var shopId = Taro.getStorageSync('shopId');
    if(malltype =='UC'){
    	var str="UC购物车"
    	if(this.state.appmark!='xjzb'){
    		var str="商城购物车"
    	}
    	Taro.setNavigationBarTitle({title:str}) 
      var url='/mallbean/papi/v1.9/carts/'+shopId
    }
    else if(malltype == 'WUC'){
    	var str="WUC购物车"
    	if(this.state.appmark!='xjzb'){
    		var str="积分购物车"
    	}
    	Taro.setNavigationBarTitle({title:str}) 
      var url='/mallcredit/papi/v1.9/carts/'+shopId
    }
    else{
    	if(this.state.appmark!='xjzb'){
    		var str="商城购物车"
    	}
    	else{
    		var str="WGM购物车"
    	}
    	
    	Taro.setNavigationBarTitle({title:str}) 
      var url='/mall/papi/v1.9/carts/'+shopId
    }
    
    var _this=this;
    CommonJs.ajaxRequest(url,'','GET',function(res){
      var ret=res.data.cartItemList;
      var arr=[];
      if(_this.state.isdel==0){
        for(var i=0;i<ret.length;i++){
          arr.push(i);
        }
      }
      _this.setState({
        carlist: ret,
        carindex: arr,
      })
      setTimeout(function() {
        _this.gettotal();
      }, 300);

    },'wfw')
  }
  gettotal(){
    var carlist=this.state.carlist;
    var carindex=this.state.carindex;
    var total=0;
    for(var i=0;i<carindex.length;i++){
      var pri=carlist[carindex[i]].product.specialPrice;
      var num=carlist[carindex[i]].amount;
      total=total+pri*num
    }
    this.setState({
      total: total
    })
  }
  editnum(index,type){
    var carlist=this.state.carlist;
    var num=carlist[index].amount;
    if(type=='jian'){
      if(num>1){
        num=num-1;
      }
      else{
       Taro.showToast({
         title:'至少购买一件哟',
         icon: 'none',
         duration: 2000
       });
       return false;
      }
    }
    else{
      if(num>=carlist[index].product.stockAmount){
        Taro.showToast({
          title:'库存没那么多了',
          icon: 'none',
          duration: 2000
        });
        return false;
      }
      else{
        num=parseInt(num)+1;
      }
    }
    var _this=this;
    var malltype = _this.state.malltype
    if(malltype =='UC'){
      var url='/mallbean/papi/v1.9/carts/cartItem'
    }
    else if(malltype == 'WUC'){
      var url='/mallcredit/papi/v1.9/carts/cartItem'
    }
    else{
      var url='/mall/papi/v1.9/carts/cartItem'
    }
    var dates={
      "amount": num,
      "id":carlist[index].cartItemId.id
    }
    CommonJs.ajaxRequest(url,dates,'PUT',function(res){
      carlist[index].amount=num;
      _this.setState({
        carlist:carlist
      })
      setTimeout(function() {
        _this.gettotal();
      }, 300);
    },'wfw')
  }
  editcar(index,type){
    var carindex=this.state.carindex;
    var _this=this;
    var wz=carindex.indexOf(index);
    if(type=='del'){
      carindex.splice(wz,1);
    }
    else{
      carindex.push(index);

    }
    this.setState({
      carindex:carindex
    })
    setTimeout(function() {
      _this.gettotal();
    }, 300);
  }
  delcar(index){
    var ids=[];
    var carindex=this.state.carindex;
    if(carindex.length==0){
      Taro.showToast({
        title:'请选择需要删除的商品',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    var carlist=this.state.carlist;
    for(var i=0;i<carindex.length;i++){
      var index=carindex[i];
      var id=carlist[index].cartItemId.id
      ids.push(id);
    }
    var _this=this;
    var malltype = _this.state.malltype
    if(malltype =='UC'){
      var url='/mallbean/papi/v1.9/carts/deleteCartItemList?cartItemIds='+ids.toString();
    }
    else if(malltype == 'WUC'){
      var url='/mallcredit/papi/v1.9/carts/deleteCartItemList?cartItemIds='+ids.toString();
    }
    else{
      var url='/mall/papi/v1.9/carts/deleteCartItemList?cartItemIds='+ids.toString();
    }
    
    CommonJs.ajaxRequest(url,'','DELETE',function(res){
      _this.setState({
        isdel:1
      })
      setTimeout(function() {
        _this.getcar(malltype);
      }, 300);
    },'wfw')
  }
  buynow(){
    var ids=[];
    var carindex=this.state.carindex;
    if(carindex.length==0){
      Taro.showToast({
        title:'请选择需要购买的商品',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    var carlist=this.state.carlist;
    var query=[];
    for(var i=0;i<carindex.length;i++){
      var obj={};
      var res=carlist[carindex[i]];
      obj.name=res.product.name;
      obj.logoUrl=res.product.logoUrl;
      obj.amount=res.amount;
      obj.itemId=res.product.itemId;
      obj.itemSkuId=res.product.itemSkuId;
      obj.price=res.product.specialPrice;
      obj.ggname=res.product.specification;
      obj.weight=res.product.weight?res.product.weight:0;
      obj.cartItemId=res.cartItemId.id;
      obj.malltype = this.state.malltype;
      obj.agentShopId=carlist[0].product.shopId
      query.push(obj)
    }
//  Taro.showToast({
//    title:'暂未开通，敬请期待',
//    icon: 'none',
//    duration: 2000
//  });
    this.open('/pages/mall/order',query)
  }
  render () {
    const carlist=this.state.carlist;
    const carindex=this.state.carindex;
    const total=this.state.total;
    return (
      <View className='page footpage'>
        <View className='mallPage shopcarPage'  style={carlist.length>0?'display:block':'display:none;'} >
        {carlist.map((item, index) => (
        <View className='shopcar-li'>
          <View className='shopcar-dt'>
            <Image className="carimg"  onClick={this.editcar.bind(this,index,'del')} mode="widthFix" src={lbicon} style={carindex.indexOf(index)>=0?'display:block':'display:none;'}></Image>
            <Image className="carimg"  onClick={this.editcar.bind(this,index,'add')} mode="widthFix" src={lbicon2} style={carindex.indexOf(index)<0?'display:block':'display:none;'}></Image>
          </View>
           <View className='shopcar-dd'>
            <View className='goods-li'>
              <View className='cat-li-img'>
                <Image className="cat-img" mode="scaleToFill" src={item.product.logoUrl?item.product.logoUrl:'https://minichat.g2ma.com/kedouimg/A6984900727459logo.png'}></Image>
              </View>
              <View className='sp-info'>
                <Text className='sp-name'>{item.product.name}</Text>
                <Text className='sp-gg'>规格：{item.product.specification?item.product.specification:'默认规格'}</Text>
                <Text className='sp-jg' style={this.state.malltype?'display:none':''}>￥{item.product.specialPrice/100}</Text>
                <Text className='sp-jg' style={this.state.malltype =='UC'?'':'display:none'}>UC{item.product.specialPrice/100}</Text>
                <Text className='sp-jg' style={this.state.malltype =='WUC'?'':'display:none'}>WUC{item.product.specialPrice/100}</Text>
              </View>
              <View className='choose-sl'>
                <Text className='jian' onClick={this.editnum.bind(this,index,'jian')}>-</Text>
                <Text className='input'>{item.amount}</Text>
                <Text className='jia' onClick={this.editnum.bind(this,index,'jia')}>+</Text>
              </View>
            </View>
          </View>
        </View>
			 ))}
			<View className='goods-btn shopcar-btn'>
				<Text className='buynow'onClick={this.buynow.bind(this)}>立即下单</Text>
				<Text className='car-pri' style={this.state.malltype?'display:none':''}>￥{total/100}</Text>
				<Text className='car-pri' style={this.state.malltype =='UC'?'':'display:none'}>UC{total/100}</Text>
				<Text className='car-pri' style={this.state.malltype =='WUC'?'':'display:none'}>WUC{total/100}</Text>
				<Text className='del' onClick={this.delcar.bind(this,index)}>删除</Text>
			</View>
		</View>
		<View className='mallPage shopcarPage' style={carlist.length>0?'display:none':'display:block;'}>
			<View className="nodate">暂无商品</View>
		</View>
		<Shopfoot porpNav="3"></Shopfoot>
      </View>
    )
  }
}